{
 "cells": [
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "9c48213d-6e6a-4c10-838a-2a7c710c3a05",
   "metadata": {},
   "source": [
    "# Simple Vector Store"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "50d3b817-b70e-4667-be4f-d3a0fe4bd119",
   "metadata": {},
   "source": [
    "#### Load documents, build the VectorStoreIndex"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "690a6918-7c75-4f95-9ccc-d2c4a1fe00d7",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "INFO:numexpr.utils:Note: NumExpr detected 12 cores but \"NUMEXPR_MAX_THREADS\" not set, so enforcing safe limit of 8.\n",
      "Note: NumExpr detected 12 cores but \"NUMEXPR_MAX_THREADS\" not set, so enforcing safe limit of 8.\n",
      "INFO:numexpr.utils:NumExpr defaulting to 8 threads.\n",
      "NumExpr defaulting to 8 threads.\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/Users/suo/miniconda3/envs/llama/lib/python3.9/site-packages/deeplake/util/check_latest_version.py:32: UserWarning: A newer version of deeplake (3.6.7) is available. It's recommended that you update to the latest version using `pip install -U deeplake`.\n",
      "  warnings.warn(\n"
     ]
    }
   ],
   "source": [
    "import logging\n",
    "import sys\n",
    "\n",
    "logging.basicConfig(stream=sys.stdout, level=logging.INFO)\n",
    "logging.getLogger().addHandler(logging.StreamHandler(stream=sys.stdout))\n",
    "\n",
    "from llama_index import (\n",
    "    VectorStoreIndex,\n",
    "    SimpleDirectoryReader,\n",
    "    load_index_from_storage,\n",
    "    StorageContext,\n",
    ")\n",
    "from IPython.display import Markdown, display"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "03d1691e-544b-454f-825b-5ee12f7faa8a",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# load documents\n",
    "documents = SimpleDirectoryReader(\n",
    "    \"../../../examples/paul_graham_essay/data\"\n",
    ").load_data()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "ad144ee7-96da-4dd6-be00-fd6cf0c78e58",
   "metadata": {
    "scrolled": true,
    "tags": []
   },
   "outputs": [],
   "source": [
    "index = VectorStoreIndex.from_documents(documents)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "2bbccf1d-ac39-427c-b3a3-f8e9d1d12348",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# save index to disk\n",
    "index.set_index_id(\"vector_index\")\n",
    "index.storage_context.persist(\"./storage\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "197ca78e-1310-474d-91e3-877c3636b901",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "INFO:llama_index.indices.loading:Loading indices with ids: ['vector_index']\n",
      "Loading indices with ids: ['vector_index']\n"
     ]
    }
   ],
   "source": [
    "# rebuild storage context\n",
    "storage_context = StorageContext.from_defaults(persist_dir=\"storage\")\n",
    "# load index\n",
    "index = load_index_from_storage(storage_context, index_id=\"vector_index\")"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "b6caf93b-6345-4c65-a346-a95b0f1746c4",
   "metadata": {},
   "source": [
    "#### Query Index"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "85466fdf-93f3-4cb1-a5f9-0056a8245a6f",
   "metadata": {
    "scrolled": true,
    "tags": []
   },
   "outputs": [],
   "source": [
    "# set Logging to DEBUG for more detailed outputs\n",
    "query_engine = index.as_query_engine(response_mode=\"tree_summarize\")\n",
    "response = query_engine.query(\"What did the author do growing up?\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "bdda1b2c-ae46-47cf-91d7-3153e8d0473b",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/markdown": [
       "<b>\n",
       "Growing up, the author wrote short stories, experimented with programming on an IBM 1401, nagged his father to buy a TRS-80 computer, wrote simple games, a program to predict how high his model rockets would fly, and a word processor. He also studied philosophy in college, switched to AI, and worked on building the infrastructure of the web. He wrote essays and published them online, had dinners for a group of friends every Thursday night, painted, and bought a building in Cambridge.</b>"
      ],
      "text/plain": [
       "<IPython.core.display.Markdown object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "display(Markdown(f\"<b>{response}</b>\"))"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "c80abba3-d338-42fd-9df3-b4e5ceb01cdf",
   "metadata": {},
   "source": [
    "**Query Index with SVM/Linear Regression**\n",
    "\n",
    "Use Karpathy's [SVM-based](https://twitter.com/karpathy/status/1647025230546886658?s=20) approach. Set query as positive example, all other datapoints as negative examples, and then fit a hyperplane."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "35e029e6-467b-4533-b566-a1568cc5f361",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "query_modes = [\n",
    "    \"svm\",\n",
    "    \"linear_regression\",\n",
    "    \"logistic_regression\",\n",
    "]\n",
    "for query_mode in query_modes:\n",
    "    # set Logging to DEBUG for more detailed outputs\n",
    "    query_engine = index.as_query_engine(vector_store_query_mode=query_mode)\n",
    "    response = query_engine.query(\"What did the author do growing up?\")\n",
    "    print(f\"Query mode: {query_mode}\")\n",
    "    display(Markdown(f\"<b>{response}</b>\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0bab9fd7-b0b9-4be1-8f05-eeb19bbe287a",
   "metadata": {},
   "outputs": [],
   "source": [
    "display(Markdown(f\"<b>{response}</b>\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c9f256c8-b5ed-42db-b4de-8bd78a9540b0",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "print(response.source_nodes[0].source_text)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "0da9092e",
   "metadata": {},
   "source": [
    "**Query Index with custom embedding string**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d57f2c87",
   "metadata": {},
   "outputs": [],
   "source": [
    "from llama_index.indices.query.schema import QueryBundle"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bbecbdb5",
   "metadata": {},
   "outputs": [],
   "source": [
    "query_bundle = QueryBundle(\n",
    "    query_str=\"What did the author do growing up?\",\n",
    "    custom_embedding_strs=[\"The author grew up painting.\"],\n",
    ")\n",
    "query_engine = index.as_query_engine()\n",
    "response = query_engine.query(query_bundle)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d4d1e028",
   "metadata": {},
   "outputs": [],
   "source": [
    "display(Markdown(f\"<b>{response}</b>\"))"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "d7ff3d56",
   "metadata": {},
   "source": [
    "**Use maximum marginal relevance**\n",
    "\n",
    "Instead of ranking vectors purely by similarity, adds diversity to the documents by penalizing documents similar to ones that have already been found based on <a href=\"https://www.cs.cmu.edu/~jgc/publication/The_Use_MMR_Diversity_Based_LTMIR_1998.pdf\">MMR</a> . A lower mmr_treshold increases diversity."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "60a27232",
   "metadata": {},
   "outputs": [],
   "source": [
    "query_engine = index.as_query_engine(\n",
    "    vector_store_query_mode=\"mmr\", vector_store_kwargs={\"mmr_threshold\": 0.2}\n",
    ")\n",
    "response = query_engine.query(\"What did the author do growing up?\")"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "5636a15c-8938-4809-958b-03b8c445ecbd",
   "metadata": {},
   "source": [
    "#### Get Sources"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "db22a939-497b-4b1f-9aed-f22d9ca58c92",
   "metadata": {},
   "outputs": [],
   "source": [
    "print(response.get_formatted_sources())"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "c0c5d984-db20-4679-adb1-1ea956a64150",
   "metadata": {},
   "source": [
    "#### Query Index with LlamaLogger\n",
    "\n",
    "Log intermediate outputs and view/use them."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "59b8379d-f08f-4334-8525-6ddf4d13e33f",
   "metadata": {},
   "outputs": [],
   "source": [
    "from llama_index.logger import LlamaLogger\n",
    "from llama_index import ServiceContext\n",
    "\n",
    "llama_logger = LlamaLogger()\n",
    "service_context = ServiceContext.from_defaults(llama_logger=llama_logger)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "aa281be0-1c7d-4d9c-a208-0ee5b7ab9953",
   "metadata": {},
   "outputs": [],
   "source": [
    "query_engine = index.as_query_engine(\n",
    "    service_context=service_context,\n",
    "    similarity_top_k=2,\n",
    "    # response_mode=\"tree_summarize\"\n",
    ")\n",
    "response = query_engine.query(\n",
    "    \"What did the author do growing up?\",\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7d65c9ce-45e2-4655-adb1-0883470f2490",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# get logs\n",
    "service_context.llama_logger.get_logs()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c1c5ab85-25e4-4460-8b6a-3c119d92ba48",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.16"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
